import cv2
import numpy as np
import os ,sys ,pathlib
root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))


def resize_image(image, width = 800 ):
    h, w, _ = image.shape
    height=int(width*(w/h))
    top, bottom, left, right = (0,0,0,0)
    return cv2.resize(image, (height, width))
def MT(img,template,threshold = 0.7):
    #img_rgb = cv2.imread(str(root/"img/20210623-00100001.jpg")) 
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)   #创建一个原始图像的灰度版本，所有操作在灰度版本中处理，然后在RGB图像中使用相同坐标还原 
    w, h = template.shape[::-1]
    imgShape=img.shape

    #使用matchTemplate对原始灰度图像和图像模板进行匹配
    res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
    #设定阈值
    
    #res大于70%
    loc = np.where( res >= threshold)
    if(len(loc[1])==0):
        return False
    elif((loc[0][0] > imgShape[0]/3) or (loc[1][0]>imgShape[1]/3)):
        return False
    else:
        '''
        print(loc[0][0])
        print(loc[1][0])
        #使用灰度图像中的坐标对原始RGB图像进行标记
        for pt in zip(*loc[::-1]):
            cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,0,255), 5)
        cv2.imshow('Detected',resize_image(img,900))
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        '''
        return True
if __name__ == "__main__":
    template = cv2.imread(str(root/'t.jpg')) 
    template = cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)

    cv2.waitKey(0)
    for dir_path, subpaths, files in os.walk(root/"img", True):
        for filename in files:
            
            pid=int(filename[-7:-4])
            MT(cv2.imread(str(root/f"img/{filename}")),template)

